import { ref } from 'vue';

export function useWebSocket(playerId, handlers) {
  const ws = ref(null);
  const isConnected = ref(false);
  
  const connect = () => {
    ws.value = new WebSocket(`ws://localhost:8080/chart/${playerId}`);
    
    ws.value.onopen = () => {
      isConnected.value = true;
      console.log('WebSocket connected');
    };
    
    ws.value.onmessage = (event) => {
      try {
        const response = JSON.parse(event.data);
        const handler = handlers[response.type];
        if (handler) handler(response.data);
        else console.warn(`Unknown message type: ${response.type}`);
      } catch (error) {
        console.error('Failed to parse WebSocket message:', error);
      }
    };
    
    ws.value.onclose = () => {
      isConnected.value = false;
      console.log('WebSocket disconnected');
    };
    
    ws.value.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
  };
  
  const sendMessage = (type, data) => {
    if (isConnected.value) {
      ws.value.send(JSON.stringify({ type, data }));
    } else {
      console.warn('WebSocket not connected, cannot send message');
    }
  };
  
  return {
    connect,
    sendMessage,
    isConnected
  };
}